package com.noriental.okcalls.wechat.callback;

import com.noriental.okcalls.wechat.config.WxApiConfigInstance;
import com.noriental.okcalls.wechat.kit.MsgEncryptKit;
import com.noriental.okcalls.wechat.msg.in.InMsg;
import org.apache.commons.lang3.StringUtils;

/***
 * *   ____  ___________  ___________           ________   ____  __.  _____ _____.___.
 * *   \   \/  /\______ \ \_   _____/           \_____  \ |    |/ _| /  _  \\__  |   |
 * *    \     /  |    |  \ |    __)     ______   /   |   \|      <  /  /_\  \/   |   |
 * *    /     \  |    `   \|     \     /_____/  /    |    \    |  \/    |    \____   |
 * *   /___/\  \/_______  /\___  /              \_______  /____|__ \____|__  / ______|
 * *    	 \_/        \/     \/                       \/        \/       \/\/
 * *
 * *   功能描述：
 * *
 * *   @DATE    2020-10-09
 * *   @AUTHOR  qiyubin
 ***/
public class MsgAdapter {


    public static InMsg analysisMsg(String xml) {
        // 解析消息并根据消息类型分发到相应的处理方法
        InMsg inMsg = InMsgParser.parse(getInMsgXml(xml));
        return inMsg;
    }


    public static InMsg analysisMsg(String xml, String t, String n, String s) {
        // 解析消息并根据消息类型分发到相应的处理方法
        InMsg inMsg = InMsgParser.parse(getInMsgXmlSafe(xml, t, n, s));
        return inMsg;
    }


    //todo 待优化
    public static String getInMsgXml(String inMsgXml) {
        // 是否需要解密消息
        if (WxApiConfigInstance.apiConfig.isEncryptMessage()) {
            throw new RuntimeException("缺少t、n、s参数");
        }
        if (StringUtils.isBlank(inMsgXml)) {
            throw new RuntimeException("请不要在浏览器中请求该连接,调试请查看WIKI:http://git.oschina.net/jfinal/jfinal-weixin/wikis/JFinal-weixin-demo%E5%92%8C%E8%B0%83%E8%AF%95");
        }
        return inMsgXml;
    }

    public static String getInMsgXmlSafe(String inMsgXml, String t, String n, String s) {
        // 是否需要解密消息
        if (WxApiConfigInstance.apiConfig.isEncryptMessage()) {
            inMsgXml = MsgEncryptKit.decrypt(inMsgXml,
                    t, n, s);
        }
        if (StringUtils.isBlank(inMsgXml)) {
            throw new RuntimeException("请不要在浏览器中请求该连接,调试请查看WIKI:http://git.oschina.net/jfinal/jfinal-weixin/wikis/JFinal-weixin-demo%E5%92%8C%E8%B0%83%E8%AF%95");
        }
        return inMsgXml;
    }


}
